<template>
    <div class="search-box">
        <i class="iconfont icon-search" @click="search"></i>
        <transition name="move" appear>
            <input ref="query"
                   type="text"
                   v-model="query"
                   class="box"
                   :placeholder="placehoder"
                   @keyup.13="search"
            >
        </transition>
        <i v-show="query" class="iconfont icon-cross" @click="clear"></i>
    </div>
</template>

<script type="text/ecmascript-6">
    import { debounce } from 'common/js/util'
    import { DEBOUNCE_TIME } from 'common/js/config'

    export default {
        name: 'search-box',
        data() {
            return {
                query: ''
            }
        },
        created() {
            this.$watch('query', debounce((newQuery) => {
                this.$emit('query', newQuery)
            }, DEBOUNCE_TIME))
        },
        props: {
            inputValue: {
                type: String,
                default: ''
            },
            placehoder: {
                type: String,
                default: '搜索音乐...'
            }
        },
        watch: {
            inputValue(newQuery) {
                this.setQuery(newQuery)
            }
        },
        methods: {
            clear() {
                this.query = ''
                this.$emit('clear')
            },
            setQuery(query) {
                this.query = query
            },
            blur() {
                this.$refs.query.blur()
            },
            search() {
                this.$emit('search', this.query)
            }
        }
    }
</script>

<style scoped lang="stylus" rel="stylesheet/stylus">
    @import "~common/stylus/variable"

    .search-box
        position: relative
        display: flex
        align-items: center
        box-sizing: border-box
        padding: 0 10px
        width: 100%
        height: 31px
        border-radius: 15px
        background: $color-background-w
        .icon-search
            font-size: 18px
            color: $color-text-d

        .move-enter-active
            transition: all .3s
        .move-enter
            transform: translate3d(60px, 0, 0)
        .box
            flex: 1
            padding: 0 10px
            line-height: 18px
            background: $color-background-w
            color: $color-text
            font-size: $font-size-medium
            caret-color: $color-theme
            outline: 0
            &::placeholder
                color: $color-text-l
        .icon-cross
            font-size: 16px
            color: $color-text-d
</style>